const express = require("express")
const app = express()
const path = require("path")
const session = require("express-session")
const jwt = require("jsonwebtoken")
const db = require("../db")
const Redis = require("../utils/redis")

const cors = require("cors")
const winston = require('winston')
const expressWinston = require('express-winston');
const tokenVerify = require("./tokenUrl");
const Base = require("./base")
//中间件
function use() {
    //日志
   /* app.use(expressWinston.logger({
        transports: [
            new winston.transports.Console()
        ],
        format: winston.format.combine(
            winston.format.colorize(),
            winston.format.json()
        ),
        meta: true, // optional: control whether you want to log the meta data about the request (default to true)
        msg: "HTTP {{req.method}} {{req.url}}", // optional: customize the default logging message. E.g. "{{res.statusCode}} {{req.method}} {{res.responseTime}}ms {{req.url}}"
        expressFormat: true, // Use the default Express/morgan request formatting. Enabling this will override any msg if true. Will only output colors with colorize set to true
        colorize: false, // Color the text and status code, using the Express/morgan color palette (text: gray, status: default green, 3XX cyan, 4XX yellow, 5XX red).
        ignoreRoute: function (req, res) { return false; } // optional: allows to skip some log messages based on request and/or response
    }));*/
    //session
    app.use(session({
        secret: 'your-secret',
        resave: false,
        saveUninitialized: true,
    }))
    //跨域
    app.use(cors())
    // json请求
    app.use(express.json())
    // 静态资源文件
    app.use("/static", express.static(path.join(__dirname,"../static")))
    app.use(async (req, res, next) => {
        try {
            // 数据库
            req.db = db
            // redis
            req.redis = new Redis()
            // base64 加密解密算法
            req.base64 = new Base()
            next()
        } catch (e) {
            next(e)
        }
    })
    // token校验中间件
    app.use(async (req, res, next) => {
        try {
            const {url, headers: {
                token
            }} = req
            //管理端token验证
            if (url.includes('ums')) {
                if (tokenVerify(url, "ums")) {
                    return next()
                }
                const {err, data} = await jwtPromise(token, "ec")
                if (err && err.message === 'invalid token') {
                    return res.status(500).send({message: '无效 token', status: 500, data: null})
                }
                if (err && err.message === 'jwt expired') {
                    return res.status(500).send({message: 'token 失效', status: 500, data: null})
                }
                // console.log(data)
                //data.username
                const [rows]  = await db.query(`SELECT * FROM ums_user WHERE username LIKE '${data.username}'`)
                if (rows) {
                    req.jwt = data
                    req.rows = rows
                    next()
                    return;
                }else {
                    return res.status(500).send({message: 'token错误', status: 500, data: null})
                }
            }

            if (url.includes("sms")) {
                // console.log(token)
                // console.log(url)
                if (tokenVerify(url, "sms")) {
                    return next()
                }
                const {err, data} = await jwtPromise(token, "sms")
                if (err && err.message === 'invalid token') {
                    return res.status(500).send({message: '无效 token', status: 500, data: null})
                }
                if (err && err.message === 'jwt expired') {
                    return res.status(500).send({message: 'token 失效', status: 500, data: null})
                }
                if (data) {
                    const rows  = await db.query(`SELECT * FROM sms_user WHERE id LIKE '${data.id}'`)
                    if (rows.length) {
                        req.jwt = data
                        req.rows = rows[0]
                        return next()
                    }else {
                        return res.status(500).send({message: 'token错误', status: 500, data: null})
                    }
                }

            }

            return next()
        } catch (e) {
            console.log(e)
        }

    })
    return app
}


function jwtPromise (token, key) {
    return new Promise( (resolve, reject) => {
        jwt.verify(token, key, (err, data) => {
            resolve({err, data})
        })
    })
}

async function val (key, tableName, req, res, next) {
    const {url, headers: {
        token
    }} = req
    if (tokenVerify(url, key)) {
        return next()
    }
    const {err, data} = await jwtPromise(token, key)
    if (err && err.message === 'invalid token') {
        return res.status(500).send({message: '无效 token', status: 500, data: null})
    }
    if (err && err.message === 'jwt expired') {
        return res.status(500).send({message: 'token 失效', status: 500, data: null})
    }
    const [rows]  = await db.query(`SELECT * FROM ${tableName} WHERE username LIKE '${data.username}'`)
    if (rows) {
        req.jwt = data
        req.rows = rows
        return next()
    }else {
        return res.status(500).send({message: 'token错误', status: 500, data: null})
    }
}

module.exports = use
